package com.zh.common.excel;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @ClassName TestEasyExcelController
 * @date: 2021.02.03 10:36
 * @Author: zhanghang
 */
@Controller
public class TestEasyExcelController {

    /**
     * description: 导出
     * date: 2021年-02月-03日 10:57
     * author: zhanghang
     * 
     * @param response
     * @return void
     */ 
    @GetMapping("/export")
    @ApiOperation(value = "导出", notes = "导出")
    public void export(HttpServletResponse response) throws IOException {
        System.out.println("=========start- export==========");
        List<TestUser> userList = getTestUser();
        write(userList,TestUser.class,response);
        System.out.println("=========end- export==========");
    }

    //示例写入并下载单个Sheet写法
    public static <T> void write(List<T> list, Class<T> clazz, HttpServletResponse response) throws IOException {
        //设置文件名等信息
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(new SimpleDateFormat("yyyyMMddHHmm").format(new Date()), "UTF-8").replaceAll("\\+", "%20") + ".xlsx");
        response.setCharacterEncoding("utf-8");
        //创建Sheet
        WriteSheet writeSheet = EasyExcel.writerSheet("Sheet1").build();
        //创建Writer
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), clazz).build();
        //写入Excel
        excelWriter.write(list, writeSheet);
        //导出文件并关闭流,清除缓存等
        excelWriter.finish();
    }

    // 封装返回数据
    private List<TestUser> getTestUser(){
        List<TestUser> list = new ArrayList<>();
        list.add(new TestUser(1L,"张三",10, DateUtil.parse("2000-01-02")));
        list.add(new TestUser(2L,"李四",20,DateUtil.parse("1999-05-02")));
        list.add(new TestUser(3L,"王五",30,DateUtil.parse("2001-06-02")));
        list.add(new TestUser(4L,"赵六",40,DateUtil.parse("2002-07-02")));
        list.add(new TestUser(5L,"小七",50,DateUtil.parse("2003-08-02")));
        list.add(new TestUser(6L,"小巴",60,DateUtil.parse("2004-09-02")));
        list.add(new TestUser(7L,"小九",70,DateUtil.parse("2005-10-02")));
        return list;
    }
}
